package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.FreezeMapper;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private FreezeMapper freezeMapper;


    //查询用户列表
    public PageResult users(Integer page, Integer pagesize) {

        //1.调用API分页查询用户信息（返回值IPage）
        IPage pages = userInfoApi.findAll(page, pagesize);
        //构造返回
        return new PageResult(page, pagesize, pages.getTotal(), pages.getRecords());
    }

    //根据id查询用户详情
    public UserInfo findByUserId(Long userId) {
        return userInfoApi.findById(userId);
    }

    //查询用户的视频列表(分页查询)
    public PageResult findVideos(Long userId, Integer page, Integer pagesize) {
        //1.调用API查询findVideo
        PageResult result = videoApi.findVideos(userId, page, pagesize);
        //2.对视频数据集合进行判断是否存在
        List<Video> items = (List<Video>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return result;
        }
        //3.存在，PageResult中的Video转换成VideoVo
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<VideoVo> vos = new ArrayList<>();
        for (Video item : items) {
            UserInfo info = map.get(item.getUserId());//视频作者的信息
            VideoVo vo = VideoVo.init(info, item);
            vos.add(vo);
        }
        //将List<VideoVo>替换到PageResult的List集合
        result.setItems(vos);
        //4.构建返回值
        return result;
    }

    //分页查询动态列表
    public PageResult findMovements(Integer status, Long userId, Integer page, Integer pagesize) {
        //1.调用api查询动态
        PageResult result = movementApi.findAll(status, userId, page, pagesize);
        //2.获取result中获取List    List<Movement>
        List<Movement> items = (List<Movement>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return result;
        }
        //3.将items转换成MovementVo
        //获取动态的所有用户id
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo info = map.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(info, item);
            vos.add(vo);
        }
        //将转换的vo替换到result中
        result.setItems(vos);
        return result;
    }

    //根据动态id查询详情
    public MovementsVo findMovement(String movementId) {
        Movement movement = movementApi.findById(movementId);
        Long userId = movement.getUserId();
        UserInfo info = userInfoApi.findById(userId);
        return MovementsVo.init(info, movement);
    }

    //查询动态评论
    public PageResult findComments(Integer page, Integer pagesize, String messageId) {
        Integer commentType = 2;
        PageResult result = commentApi.findMovComments(page, pagesize, commentType, messageId);
        List<Comment> items = (List<Comment>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<CommentVo> vos = new ArrayList<>();
        for (Comment item : items) {
            UserInfo info = map.get(item.getUserId());
            CommentVo vo = CommentVo.init(info, item);
            vos.add(vo);
        }
        result.setItems(vos);
        return result;
    }

    //用户冻结
    public String freeze(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        //根据用户id查询出冻结信息
        QueryWrapper<Freeze> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        Freeze freeze = freezeMapper.selectOne(qw);
        //判断freeze是否为空
        if (freeze == null) {
            //等于空 新建 并封装冻结信息
            freeze = new Freeze(userId, freezingTime, freezingRange, reasonsForFreezing, frozenRemarks);
            //判断冻结时间 冻结时间freezingTime，1为冻结3天，2为冻结7天，3为永久冻结
            if (freezingTime == 1) {
                freeze.setUnfreezeTime(getDateAfter(new Date(),3));
            }
            if (freezingTime == 7) {
                freeze.setUnfreezeTime(getDateAfter(new Date(),7));
            }
            freezeMapper.insert(freeze);
//            //将用户状态userStatus改为2  用户状态,1为正常，2为冻结
//            UserInfo userInfo = userInfoApi.findById(userId);
//            userInfo.setUserStatus("2");
//            userInfoApi.update(userInfo);
        } else {
            //不等于空更新
            freeze.setFreezingTime(freezingTime);
            freeze.setFreezingRange(freezingRange);
            freeze.setReasonsForFreezing(reasonsForFreezing);
            freeze.setFrozenRemarks(frozenRemarks);
            //判断冻结时间 冻结时间freezingTime，1为冻结3天，2为冻结7天，3为永久冻结
            if (freezingTime == 1) {
                freeze.setUnfreezeTime(getDateAfter(new Date(),3));
            }
            if (freezingTime == 7) {
                freeze.setUnfreezeTime(getDateAfter(new Date(),7));
            }
            freezeMapper.updateById(freeze);
//            //将用户状态userStatus改为2  用户状态,1为正常，2为冻结
//            UserInfo userInfo = userInfoApi.findById(userId);
//            userInfo.setUserStatus("2");
//            userInfoApi.update(userInfo);
        }
        //将用户状态userStatus改为2  用户状态,1为正常，2为冻结
        UserInfo userInfo = userInfoApi.findById(userId);
        userInfo.setFreezingRange(freezingRange);
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        return "冻结成功";
    }

    /**
     * 得到几天后的时间
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d, int day){

        Calendar now =Calendar.getInstance();

        now.setTime(d);

        now.set(Calendar.DATE,now.get(Calendar.DATE)+day);

        return now.getTime();

    }

    //用户解冻
    public String unfreeze(Long userId, String reasonsForThawing) {
        //根据用户id查询出冻结信息
        QueryWrapper<Freeze> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        Freeze freeze = freezeMapper.selectOne(qw);
        if (freeze == null) {
            //未查出 提示错误
            throw new BusinessException("冻结信息不存在");
        } else {
            freeze.setReasonsForThawing(reasonsForThawing);
            freeze.setUnfreezeTime(null);// 将时间设置为空
            freezeMapper.updateById(freeze);
        }
        //将用户状态改为正常
        UserInfo userInfo = userInfoApi.findById(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        return "解冻成功";
    }
}
